<template>
	<view class="container">
		<view class="p010 bg">
			<view class="xf-wrap">
				<view class="box-shadow p1015 m5 mb20">
					<view class="uni-flex uni-row">
						<view class="flex-item mb20">
							<view>
								<text class="sign-num">城市</text>
								<view class="inline-flex">
									<picker mode="multiSelector" :range="citys" :range-key="'name'" :value="multiIndex" @change="bindRegionChange" @columnchange="bindRegionColumnChange">
										<view class="picker font_size_36">
											{{locationCityName}}
										</view>
									</picker>
								</view>
							</view>
						</view>
						<view class="flex-item mb20">
							<view>
								<text class="sign-num">集合时间</text>
								<view class="inline-flex">
									<picker mode="date" :value="date" :start="startDate" :end="endDate"
										@change="bindDateChange">
										<view class="uni-input font_size_36">{{date}}</view>
									</picker>
								</view>
							</view>
						</view>
					</view>
					<view class="search">
						<button class="search_btn" type="success" @tap="navgetTo('pages/index/team',locationCityName,'')">搜索队伍</button>
					</view>
				</view>
			</view>
		</view>
		<view class="bottom-wrap">
			<view class="sticky">
				<text>同城队伍</text><uni-icons type="location-filled" size="20" color="#888"></uni-icons>{{param.locationCityName}}
			</view>
			<view class="uni-padding-wrap pt30">
				<view class="foot-list uni-flex uni-row" v-if="List.length>0">
					<view class="foot-card m5" v-for="item in List" @tap="navgetTo('pages/schdule/schdule_detail',item.id)">
						<image class="foot-avatar" :src="item.coverUrl"></image>
						<view class="p010">
							<text class="foot-name">{{item.itineraryTitle}}</text>
							<view class="uni-flex">
								<text class="sign-num">已报{{item.memberCount}}/{{item.userLimit}}</text>
								<view class="sign-price-list"><text class="sign-price">{{item.itineraryFee}}</text>元/人</view>
							</view>
							<view class="sign-time">
								<text>{{item.collectDate}}集合</text>
							</view>
						</view>
					</view>
				</view>
				<!-- 加载提示 -->
				 <view class="tc mb100">{{loadMoreText}}</view>
			</view>
		</view>
	</view>
</template>

<script>
	import api from '@/common/api/webapi.js'; /*api*/
	import storageUtil from '@/common/util/storageUtil.js';
	export default {
		components: {
			
		},
		data() {
			const currentDate = this.getDate({
				format: true
			})
			return {
				date: currentDate,
				citys: [[],[]],
				customItem: '',
				loadMoreText:"",
				locationCityName:'',
				cityCode:'',
				provinceCode:'',
				multiIndex:[0,0],
				List:[],
				param: {
					page: 1, //当前页
					limit: 10, //每页显示记录数
					PageCount: 0,
					latitude: 25.040609, //默认为昆明市经纬度坐标
					longitude: 102.712251, //默认为昆明市经纬度坐标
					cityCode:0,
					locationCityName:"",
					collectDate:"",
				},
			}
		},
		computed: {
			startDate() {
				return this.getDate('start');
			},
			endDate() {
				return this.getDate('end');
			}
		},
		watch: {

		},
		onShow() {
			// 处理分享参数
			this.handleShareParams();
			this.param.page = 1;
			this.getRegionList();
			this.checkGetPosition();
			// 返回首页时重新加载数据，确保订单状态变更后列表能更新
			this.param.page = 1;
			this.getPageList('onPullDownRefresh');
		},
		onPullDownRefresh() {
			// 下拉刷新时触发的逻辑
			this.param.page = 1;
			this.getPageList('onPullDownRefresh');
		},
		onReachBottom() {
		    // 触发加载更多逻辑
		    this.param.page = (this.param.page + 1);
			if (this.param.page > this.param.PageCount) {
				this.loadMoreText = "--到底啦--"
				return;
			}
			this.getPageList('onReachBottom');
		},
		onLoad(option) {
			this.param.page = 1;
			this.getRegionList();
			this.checkGetPosition();
		},
		methods: {
			getCityCode(){
				// 通过当前城市名称获取对应城市的所属省份id和城市id
				api.getCityCode({params:{cityName:this.locationCityName}}).then(res => {
					if (res.code === 0) {
						if (res.data) {
							this.provinceCode = res.data.provinceCode;
							this.cityCode = res.data.cityCode;
							this.param.cityCode = res.data.cityCode;
							this.getCitysList(this.provinceCode);
							this.param.page = 1;
							this.getPageList('onPullDownRefresh');
						}
					}
				}).catch(e => {
					console.error('获取省份列表失败:', e);
				});
			},
			checkGetPosition(){
				let locationCityName = storageUtil.getStorageData('locationCityName');
				if(locationCityName != null && locationCityName != undefined && locationCityName != ""){
					this.locationCityName = locationCityName;
					this.param.locationCityName = locationCityName;
					this.getCityCode();
				}else{
					// 获取定位信息
					uni.getLocation({
						success: (res) => {
							if(res.errMsg == "getLocation:fail auth deny"){//用户拒绝授权
								uni.showToast({
									icon: 'none',
									title: '需要授权定位才能查看您的同城行程哦！'
								});
								// 设置默认城市（昆明），确保用户能看到数据
								this.setDefaultCity();
							}else{
								console.log(res);
								this.param.latitude = res.latitude;
								this.param.longitude = res.longitude;
								storageUtil.saveStorageData("longitude", res.longitude);//当前定位经度
								storageUtil.saveStorageData("latitude", res.latitude);//当前定位纬度
								this.getUserAddress();
							}
						},
						fail: (res) => {
							console.log('定位失败！', res);
							// 定位失败时设置默认城市
							this.setDefaultCity();
						}
					});
				}
			},
			// 设置默认城市（昆明），确保在定位失败或无法获取城市信息时能显示数据
			setDefaultCity() {
				// 尝试从本地存储获取之前保存的城市信息
				let savedCityName = storageUtil.getStorageData('locationCityName');
				let savedCityCode = storageUtil.getStorageData('cityCode');
				
				if (savedCityName && savedCityCode) {
					this.locationCityName = savedCityName;
					this.param.locationCityName = savedCityName;
					this.param.cityCode = savedCityCode;
					this.getPageList("onPullDownRefresh");
				} else {
					// 如果没有保存的城市信息，使用默认城市（昆明）
					this.locationCityName = "昆明市";
					this.param.locationCityName = "昆明市";
					this.param.cityCode = 530100;
					// 立即获取数据，确保页面不会空白
					this.getPageList("onPullDownRefresh");
					// 同时尝试重新获取省份数据
					this.getRegionList();
				}
			},
			
			// 获取省份列表数据
			getRegionList() {
				api.getRegionList().then(res => {
					if (res.code === 0) {
						if (res.data && res.data.length > 0) {
							this.citys[0] = res.data;
							// 保存省份数据到本地存储
							storageUtil.saveStorageData("region", JSON.stringify(res.data));
						}
					}
				}).catch(e => {
					console.error('获取省份列表失败:', e);
				});
			},
			checkIsLogin() {
				// let userLoginFlag = storageUtil.getStorageData("isLogin");

				// if (!userLoginFlag || userLoginFlag == '') {
				// 	this.popShowHandle();
				// 	return;
				// }
			},
			bindDateChange: function(e) {
				this.date = e.detail.value;
				this.param.page = 1;
				this.getPageList('onPullDownRefresh');
			},
			getDate(type) {
				const date = new Date();
				let year = date.getFullYear();
				let month = date.getMonth() + 1;
				let day = date.getDate();
				if (type === 'start') {
					year = year;
				} else if (type === 'end') {
					if (month > 6) {
						year = year + 1;
					}
					year = year;
				}
				month = month > 9 ? month : '0' + month;
				day = day > 9 ? day : '0' + day;
				return `${year}-${month}-${day}`;
			},
			// 城市选择
			bindRegionChange(e) {
				let provkey = e.detail.value[0];
				let citykey = e.detail.value[1];
				this.locationCityName = this.citys[1][citykey]['name'];
				this.cityCode = this.citys[1][citykey]['code'];
			},
			// 省份列选择事件
			bindRegionColumnChange(e){
				if(e.detail.column == 0){
					let proviceKey = e.detail.value;
					let curProviceCode = this.citys[0][proviceKey];
					this.getCitysList(curProviceCode['code']);
				}
			},
			getCitysList(pid){
				api.getCitysList({params:{code:pid}}).then(res => {
					if (res.code === 0) {
						if (res.data.length > 0) {
							let datas = res.data;
							console.log("cityData",res.data);
							this.citys[1]=res.data;
							console.log(this.provinceCode,this.cityCode);
							let provicekey = this.citys[0].findIndex(item => item.code === this.provinceCode);
							let citykey = this.citys[1].findIndex(item => item.code === this.cityCode);
							console.log("provicekey",provicekey);
							console.log("citykey",citykey);
							this.multiIndex = [provicekey,citykey];
						}
					} else {}
				}).catch()
			},
			// 处理分享参数
			handleShareParams() {
				try {
					// 检查是否已经处理过分享参数，避免无限循环
					const hasProcessedShare = storageUtil.getStorageData("hasProcessedShare");
					if (hasProcessedShare === "true") {
						// 已经处理过，清除标记
						storageUtil.removeStorageData("hasProcessedShare");
						return;
					}
					
					// 获取保存的分享参数
					const shareParamsStr = storageUtil.getStorageData("shareParams");
					const scanParamsStr = storageUtil.getStorageData("scanParams");
					
					if (shareParamsStr || scanParamsStr) {
						console.log('首页处理分享参数:', { shareParamsStr, scanParamsStr });
						
						// 设置已处理标记
						storageUtil.saveStorageData("hasProcessedShare", "true");
						
						// 优先处理扫码参数
						if (scanParamsStr) {
							const scanParams = JSON.parse(scanParamsStr);
							// 根据扫码参数进行跳转
							if (scanParams.schduleId || scanParams.teamId) {
								// 跳转到行程详情或团队详情
								const targetPage = `/pages/schdule/schdule_detail?schduleId=${scanParams.schduleId}` 
								uni.navigateTo({ url: targetPage });
								return;
							}
						}
						
						// 处理分享链接参数
						if (shareParamsStr) {
							const shareParams = JSON.parse(shareParamsStr);
							// 根据分享参数进行跳转
							if (shareParams.schduleId || shareParams.teamId) {
								// 跳转到行程详情或团队详情
								const targetPage = `/pages/schdule/schdule_detail?schduleId=${shareParams.schduleId}`
								uni.navigateTo({ url: targetPage });
								return;
							}
						}
					}
				} catch (e) {
					console.error('首页处理分享参数失败:', e);
				}
			},
			// 详情
			navgetTo(page, param, type) {
				if (param != undefined) {
					type = type || '';
					let data = {
						data: param,
						page: type
					}
					uni.navigateTo({
						url: "/" + page + "?param=" + encodeURI(JSON.stringify(data))
					});
				} else {
					uni.navigateTo({
						url: "/" + page
					});
				}
			},
			// 逆地址解析
			getUserAddress(){
				try {
					const app = getApp();
					if (app.globalData && app.globalData.qqmapsdk) {
						const qqmapsdk = app.globalData.qqmapsdk;
						qqmapsdk.reverseGeocoder({
							//根据经纬度获取地址信息
							location: {
								latitude: this.param.latitude,
								longitude: this.param.longitude
							},
							success: res => {
								if (res.result && res.result.ad_info && res.result.address_component) {
									this.locationCityName = res.result.address_component.city;
									this.param.locationCityName = res.result.address_component.city;
									storageUtil.saveStorageData('cityCode', res.result.ad_info.city_code);
									storageUtil.saveStorageData('locationCityName', res.result.address_component.city);
									storageUtil.saveStorageData('locationProvinceName', res.result.address_component.province);
									this.getCityCode();
									this.getPageList("onPullDownRefresh");
								} else {
									console.error('地址解析结果格式不正确');
									this.setDefaultCity();
								}
							},
							fail: (err) => {
								console.error('地址解析失败:', err);
								this.setDefaultCity();
							}
						})
					} else {
						console.error('qqmapsdk未初始化');
						this.setDefaultCity();
					}
				} catch (e) {
					console.error('地址解析异常:', e);
					this.setDefaultCity();
				}
			},
			// 获取分页列表
			getPageList(type) {
				let _this = this;
				let requestData = {
					params: {
						page: _this.param.page, //当前页
						size: _this.param.limit, //每页显示记录数
						locationCityName: _this.param.locationCityName,
						cityCode:'',
						collectDate:_this.date
					}
				}
			
				api.getItineraryPageList(requestData).then(res => {
					if (res.code === 0) {
						if (res.data.length > 0) {
							let pagelist = res.data;
							if (type == "onReachBottom") {
								_this.List = _this.List.concat(pagelist);
							} else {
								_this.List = pagelist;
							}
						}else{
							if(type == "onPullDownRefresh"){
								_this.List = [];
							}else if(type == "onReachBottom"){
								this.loadMoreText = "--到底啦--"
							}
						}
					} else {}
					// 结束下拉刷新动画
					uni.stopPullDownRefresh();
				// _this.isRefreshing = false;
				// _this.loadMoreText = "";
				}).catch(function(){
					uni.stopPullDownRefresh();
					// _this.isRefreshing = false;
					// _this.loadMoreText = "";
				})
			
			},
		}
	}
</script>

<style lang="scss" scoped>
	.container {
		font-size: 14px;
		line-height: 24px;
	}
	.bg{
		background: url('https://green-leader.oss-cn-hangzhou.aliyuncs.com/common/%E9%A6%96%E9%A1%B5%E9%A1%B6%E5%9B%BE.jpg') no-repeat top left;
		background-size: 100% auto;
		padding-top: 400rpx;
	}
	.height-150 {
		height: 150rpx;
	}

	.index-swiper {
		width: 100%;
		height: 340rpx; /* 设置合适的高度，可根据实际图片比例调整 */
		overflow: hidden;
	}
	.container::-webkit-scrollbar {
	  display: none;
	  width: 0;
	  height: 0;
	  color: transparent;
	  background: transparent;
	}

	.index-swiper image {
		width: 100%;
		height: 100%;
		object-fit: cover; /* 保持宽高比并填充整个容器 */
	}
	
	.bottom-wrap{
		position: relative;
	}
	
	.xf-wrap {
		position: relative;
	}

	.box-shadow {
		box-shadow: 2rpx 2px 20rpx $uni-text-color-grey8;
		background-color: #ffffff;
		border-radius: 20rpx;
	}

	.xf-wrap input {
		font-weight: bold;
	}

	.uni-flex {
		display: flex;
		justify-content: space-between;
	}

	.uni-row {
		flex-direction: row;
	}

	.flex-item {
		width: 50%;
		text-align: left;
		line-height: 70rpx;
	}

	.search_btn {
		background-color: $uni-text-color-green;
		font-size: 14px;
		border: none;
		color: #fff;
		height: 100rpx;
		line-height: 100rpx;
	}

	.sticky {
		height: 110rpx;
		line-height: 110rpx;
		background-color: #ffffff;
		width: 100%;
		color: #888;
		position: relative;
		top: -1rpx;
		left: 0;
		right: 0;
		z-index: 999;
		padding: 0 15px;
	}

	.sticky text {
		color: #000;
		font-weight: bold;
		margin-right: 30rpx;
	}

	.foot-list {
		width: 100%;
		display: flex;
		flex-wrap: wrap;
		justify-content: space-between;
		row-gap: 2%;
		box-sizing: border-box;
	}

	.foot-card {
		width: 47%;
		background-color: #fff;
		border-radius: 20rpx;
		position: relative;
		margin-bottom: 30rpx;
		box-shadow: 2rpx 2rpx 10rpx $uni-text-color-grey8;
		box-sizing: border-box;
	}

	.foot-avatar {
		width: 100%;
		height: 425rpx;
		border-top-right-radius: 20rpx;
		border-top-left-radius: 20rpx;
	}

	.foot-name {
		font-size: 28rpx;
		color: #000;
	}

	.sign-num {
		font-size: 24rpx;
		color: $uni-text-color-grey8;
		height: 50rpx;
		height: 50rpx;
	}
	
	.picker{
		height: 60rpx;
		line-height: 60rpx;
	}

	.sign-price-list {
		font-size: 26rpx;
		color: $uni-text-color-grey8;
	}

	.sign-price {
		color: $uni-text-color-red;
	}

	.sign-time {
		position: absolute;
		top: 10rpx;
		width: 98%;
		left: 0;
		right: 0;
		margin: auto;
		background-color: rgba(0, 0, 0, 0.6);
		height: 45rpx;
		color: #fff;
		font-size: 24rpx;
		border-radius: 20rpx;
		padding: 0 10rpx;
		box-sizing: border-box;
	}
</style>